package com.longzongqin.demo.utils;


import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class UploaderUtil {

    public static String uploadPath = "/gdpHugeFileDir";

    public static Boolean upload(MultipartFile file,String md5File,Integer chunk) { //第几片，从0开始
        String path = uploadPath+"/"+md5File+"/";
        File dirfile = new File(path);
        if (!dirfile.exists()) {//目录不存在，创建目录
            dirfile.mkdirs();
        }
        String chunkName;
        if(chunk == null) {//表示是小文件，还没有一片
            chunkName = "0.tmp";
        }else {
            chunkName = chunk+ ".tmp";
        }
        String filePath = path+chunkName;
        File savefile = new File(filePath);

        try {
            if (!savefile.exists()) {
                savefile.createNewFile();//文件不存在，则创建
            }
            file.transferTo(savefile);//将文件保存
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static Boolean checkChunk(String md5File,Integer chunk) {
        Boolean exist = false;
        String path = uploadPath+"/"+md5File+"/";//分片存放目录
        String chunkName = chunk+ ".tmp";//分片名
        File file = new File(path+chunkName);
        if (file.exists()) {
            exist = true;
        }
        return exist;
    }

    public static Boolean merge(Integer chunks, String md5File, String name) throws Exception {
        FileOutputStream fileOutputStream = new FileOutputStream(uploadPath+"/"+name);  //合成后的文件
        try {
            byte[] buf = new byte[1024];
            for(long i=0;i<chunks;i++) {
                String chunkFile=i+".tmp";
                File file = new File(uploadPath+"/"+md5File+"/"+chunkFile);
                InputStream inputStream = new FileInputStream(file);
                int len = 0;
                while((len=inputStream.read(buf))!=-1){
                    fileOutputStream.write(buf,0,len);
                }
                inputStream.close();
            }
            //合并完，要删除md5目录及临时文件，节省空间。这里代码省略
            //删除比较耗时，可能会导致响应超时，需要异步删除
            FileUtils.deleteDirectory(new File(uploadPath + "/" + md5File));

        } catch (Exception e) {
            return false;
        }finally {
            fileOutputStream.close();
        }
        return true;
    }


    public static Boolean checkFile(String md5File) {
        Boolean exist = false;

        //实际项目中，这个md5File唯一值，应该保存到数据库或者缓存中，通过判断唯一值存不存在，来判断文件存不存在
		/*if(true) {
			exist = true;
		}*/
        return exist;
    }

}

